package com.cqs.learning.spring.cloud.producer.config.sharding;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Range;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.RangeShardingValue;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;

/**
 * @Author lixw
 * @Date 6/4/20 12:55 AM
 */
@Slf4j
public class TransferRangeDateShardingStrategy implements RangeShardingAlgorithm<Timestamp> {

    private final SimpleDateFormat format = new SimpleDateFormat("yyyy");

    public static void main(String[] args) {
        Timestamp timestamp = Timestamp.valueOf("1995-01-30 16:00:00");
        System.out.println(timestamp.getYear());
    }

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, RangeShardingValue<Timestamp> shardingValue) {
        Range<Timestamp> valueRange = shardingValue.getValueRange();
        //传递过来
        Timestamp lower = valueRange.lowerEndpoint();
        Timestamp upper = valueRange.upperEndpoint();
        int minYear = NumberUtils.toInt(this.format.format(lower));
        int maxYear = NumberUtils.toInt(this.format.format(upper));
        Collection<String> tables = new ArrayList<>();
        for (int year = minYear; year <= maxYear; year++) {
            String target = shardingValue.getLogicTableName() + "_" + year;
            if (availableTargetNames.contains(target)){
                tables.add(target);
            }
        }
        if (tables.size() == 0 ){
            log.warn("没有匹配到合适的表,sharding失败{}", JSON.toJSONString(shardingValue));
        }
        return tables;
    }
}
